package leetCode;

import java.util.LinkedList;
import java.util.Queue;

public class LinkedListCycleII {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode detectCycle(ListNode head) {
        //!!!娉ㄦ剰
        if (head == null) {
            return null;
        }
        //蹇�2鎱�1锛岀洿鍒扮浉閬�
        ListNode p = head, q = head;
        while (p.next != null && p.next.next != null) {
            p = p.next.next;
            q = q.next;
            if (p == q) {
                break;
            }
        }
        if (p.next == null || p.next.next == null) {
            return null;
        }
        //p鍥瀐ead锛岃蛋涓�姝�
        p = head;
        while (p != q) {
            p = p.next;
            q = q.next;
        }
        return p;
    }
}
